<?php
/**
 * Created by PhpStorm.
 * User: 94004
 * Date: 2017/12/28
 * Time: 19:29
 */
header("Content-Type:text/html;charset=utf-8;");
require_once "config.php";

function connect() {
    $connect = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_NAME);
    mysqli_set_charset($connect, DB_CHARSET);
    return $connect;
}

function query($sql) {
    $connect = connect();
    $res = mysqli_query($connect, $sql);
    $arr = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $arr[] = $row;
    }
    return $arr;
}

function insert($table, $arr) {
    $connect = connect();
    $keys = array_keys($arr);
    $values = array_values($arr);
    $sql = " INSERT INTO {$table} (" . implode(",", $keys) . ") VALUES ('" . implode("','", $values) . "')";
    $res = mysqli_query($connect, $sql);
    return $res;
}

function delete($table, $id) {
    $connect = connect();
    $sql = " DELETE FROM {$table} WHERE id={$id} ";
    $res = mysqli_query($connect, $sql);
    return $res;
}

function update($table, $arr, $id) {
    $connect = connect();
    $sql = " UPDATE {$table} SET ";
    foreach ($arr as $key => $value) {
        $sql .= $key . "='" . $value . "',";
    }
    $sql = substr($sql, 0, -1);
    $sql .= " WHERE id={$id} ";
    $res = mysqli_query($connect, $sql);
    return $res;
}

function updatePassword($table, $newPwd, $id) {
    $connect = connect();
    $sql = " UPDATE {$table} SET password=" . $newPwd . " WHERE id = {$id} ";
    $res = mysqli_query($connect, $sql);
    return $res;
}

function updateStatusById($table, $id, $status) {
    $connect = connect();
    $sql = " UPDATE {$table} SET status={$status} WHERE id={$id}";
    $res = mysqli_query($connect, $sql);
    return $res;
}

function deleteMultipleById($table, $ids) {
    $connect = connect();
    $sql = " DELETE FROM {$table} WHERE id IN (" . implode(",", $ids) . ")";
    $res = mysqli_query($connect, $sql);
    return $res;
}


function updateMultipleById($table, $ids, $status) {
    $connect = connect();
    $sql = " UPDATE {$table} SET status={$status} ";
    $sql .= " WHERE id IN (" . implode(",", $ids) . ") ";
    $res = mysqli_query($connect, $sql);
    return $res;
}

function execute($sql) {
    $connect = connect();
    $res = mysqli_query($connect, $sql);
    return $res;
}

?>